package com.xyh.flowershop.service.impl;

import cn.hutool.json.JSONObject;
import com.xyh.flowershop.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Objects;

/**
 * @author 小约翰可汗
 * @className WechatServiceImpl
 * @createTime 2024/4/1720:25
 */
@Slf4j
@Service
public class WechatServiceImpl implements WechatService {
    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;

    /**
     * 获取openid
     * @param code
     * @return
     */
    @Override
    public JSONObject wxLogin(String code) {
        JSONObject jsonObject = null;
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+appSecret+"&js_code="+code+"&grant_type=authorization_code";
        HttpClient client  = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url))
                .header("Accept","application/json")
                .GET()
                .build();
        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            String body = response.body();

            if(!Objects.isNull(body)) jsonObject = new JSONObject(body);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
}
